package pl.msikora.android.lapmagic.database;

import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class Triggers {

	private static final String TAG = "Triggers";
	
	public static final String DELETE_TRACK = "delete_track";
	public static final String UPDATE_TRACK = "update_track";
	public static final String DELETE_SESSION = "delete_session";
	public static final String DELETE_LAP = "delete_lap";
	
	private static final String DELETE_TRACK_CREATE = "create trigger "
			+ "if not exists " + DELETE_TRACK + " before delete on "
			+ TracksTable.TABLE_TRACKS + " begin delete from "
			+ PointsTable.TABLE_POINTS + " where "
			+ PointsTable.COLUMN_TRACK_ID + " = old." 
			+ TracksTable.COLUMN_ID + "; end;";

	private static final String UPDATE_TRACK_CREATE = "create trigger "
			+ "if not exists " + UPDATE_TRACK + " before update of "
			+ TracksTable.COLUMN_ID + " on "
			+ TracksTable.TABLE_TRACKS + " begin update "
			+ PointsTable.TABLE_POINTS + " set "
			+ PointsTable.COLUMN_TRACK_ID + " = new." 
			+ TracksTable.COLUMN_ID + "; update "
			+ SessionsTable.TABLE_SESSIONS + " set "
			+ SessionsTable.COLUMN_TRACK_ID + " = new."
			+ TracksTable.COLUMN_ID + "; end;";

	private static final String DELETE_SESSION_CREATE = "create trigger "
			+ "if not exists " + DELETE_SESSION + " before delete on "
			+ SessionsTable.TABLE_SESSIONS + " begin delete from "
			+ LapsTable.TABLE_LAPS + " where "
			+ LapsTable.COLUMN_SESSION_ID + " = old." 
			+ SessionsTable.COLUMN_ID + "; end;";

	private static final String DELETE_LAP_CREATE = "create trigger "
			+ "if not exists " + DELETE_LAP + " before delete on "
			+ LapsTable.TABLE_LAPS + " begin delete from "
			+ SplitsTable.TABLE_SPLITS + " where "
			+ SplitsTable.COLUMN_LAP_SESSION_ID + " = old." 
			+ LapsTable.COLUMN_SESSION_ID + " and "
			+ SplitsTable.COLUMN_LAP_NO + " = old."
			+ LapsTable.COLUMN_LAP_NO + "; delete from " 
			+ LocationsTable.TABLE_LOCATIONS + " where "
			+ LocationsTable.COLUMN_LAP_SESSION_ID + " = old." 
			+ LapsTable.COLUMN_SESSION_ID + " and "
			+ LocationsTable.COLUMN_LAP_NO + " = old."
			+ LapsTable.COLUMN_LAP_NO + "; end;";

	public static void onCreate(SQLiteDatabase database) {
		Log.d(TAG, "creating trigger " + DELETE_TRACK + " with statement '" 
				+ DELETE_TRACK_CREATE + "'");
		database.execSQL(DELETE_TRACK_CREATE);
		
		Log.d(TAG, "creating trigger " + UPDATE_TRACK + " with statement '" 
				+ UPDATE_TRACK_CREATE + "'");
		database.execSQL(UPDATE_TRACK_CREATE);

		Log.d(TAG, "creating trigger " + DELETE_SESSION + " with statement '" 
				+ DELETE_SESSION_CREATE + "'");
		database.execSQL(DELETE_SESSION_CREATE);

		Log.d(TAG, "creating trigger " + DELETE_LAP + " with statement '" 
				+ DELETE_LAP_CREATE + "'");
		database.execSQL(DELETE_LAP_CREATE);
	}
}
